package cn.jingyuan.owl.json.fastjson.serializable;

import cn.jingyuan.owl.enums.core.EnumString;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.JSONToken;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.util.TypeUtils;

import java.io.IOException;
import java.lang.reflect.Type;

public class EnumStringSerializer implements ObjectSerializer, ObjectDeserializer {

    public static final EnumStringSerializer INSTANCE = new EnumStringSerializer();

    @Override
    public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
        Object value = parser.parse();
        Class clazz = (Class) type;
        if (null == value) {
            return null;
        }
        return (T) EnumString.valueOf(TypeUtils.castToString(value), clazz);
    }

    @Override
    public int getFastMatchToken() {
        return JSONToken.LITERAL_STRING;
    }

    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        serializer.write(((EnumString) object).getCode());
    }

}
